<?php

class CatalogeController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request

		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'uploadPhoto', 'getDestination'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','listPhoto','getListCity','setMark',
					'checkBooked','booked',
					'addBookmark','delBookmark'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	private function getCalendarData($requestParams){
		if(isset($requestParams["y"])){
			$year  = date("Y", mktime(0,0,0,$requestParams["m"],1,$requestParams["y"]));
		} else {
			$year  = date("Y", mktime(0,0,0,date('m'),1,date('Y')));
		}
		if(isset($requestParams["m"])){
			$month = date("m", mktime(0,0,0,$requestParams["m"],1,$requestParams["y"]));
		} else {
			$month = date("m", mktime(0,0,0,date('m'),1,date('Y')));
		}
	
		$skip = date("w", mktime(0,0,0,$month,1,$year)); // узнаем номер дня недели
		if($skip < 0){
			$skip = 6;
		}
		//echo $skip;exit;
		$daysInMonth   = date("t", mktime(0,0,0,$month,1,$year));       // узнаем число дней в месяце
		$calendar_head = '';    // обнуляем calendar head
		$calendar_body = '';    // обнуляем calendar boday
		$day = 1;       // для цикла далее будем увеличивать значение
		$requests = array();
		$requestsD = array();
		/*
		$id = SessionService::getAttribute(SessionService::USERS_ID);
		if(isset($id) && $id!=NULL){
			$role = SessionService::getAttribute(SessionService::ROLE);
			$req = $role == 'ER' ? RequestsService::getRequestsForER($id, NULL) : RequestsService::getRequestsForSR($id, NULL);
			foreach($req as $key => $val){
				if($val[RequestsService::RQ_STATUS] != 7 && $val[RequestsService::RQ_STATUS] !=6 && $val[RequestsService::RQ_STATUS]!=5 ){
					$y = date("Y", $val[RequestsService::RQ_DATE]);
					$m = date("m", $val[RequestsService::RQ_DATE]);
					$d = date("j", $val[RequestsService::RQ_DATE]);
					if($m==$month && $year==$y){
						$requests[] = $val[RequestsService::RQ_STATUS];
						$requestsD[] = $d;
					}
				}
			}
		}*/
		for($i = 0; $i < 6; $i++){ // Внешний цикл для недель 6 с неполыми
			$calendar_body .= '<tr>';       // открываем тэг строки
			for($j = 0; $j < 7; $j++){      // Внутренний цикл для дней недели
				if(($skip > 0)or($day > $daysInMonth)){ // выводим пустые ячейки до 1 го дня ип после полного количства дней
					$calendar_body .= '<td class="none"> </td>';
					$skip--;
				} else{
					if($j == 6){     // если воскресенье то омечаем выходной
						if ((date('j')<=$day) && date('m')==$month && date('Y')==$year|| date('m')<$month && date('Y')==$year || date('Y')<$year){
							$calendar_body .= '<td class="day holiday"><a href="#" class="chooseday" >'.$day.'</a></td>';
						} else {
							$calendar_body .= '<td class="day none"><a href="#" class="none">'.$day.'</a></td>';
						}
					} else {   // в противном случае просто выводим день в ячейке
						$key = array_search($day, $requestsD);
						if($key !== false){
							$class = $requests[$key]==2 ? 'cansel' : 'selected';
						} else {
							$class = '';
						}
						if ((date('j')==$day)&&(date('m')==$month)&&(date('Y')==$year)){//проверяем на текущий день
							$calendar_body .= '<td class="day today '.$class.'"><a href="#" class="chooseday" >'.$day.'</a></td>';
						} else {
							//echo date('Y').'-'.$year.'<br/>';
							if ((date('j')<=$day) && date('m')==$month && date('Y')==$year|| date('m')<$month && date('Y')==$year || date('Y')<$year){
								$calendar_body .= '<td class="day '.$class.'"><a href="#" class="chooseday" >'.$day.'</a></td>';
							} else {
								$calendar_body .= '<td class="day none"><a href="#" class="none">'.$day.'</a></td>';
							}
						}
					}
					$day++; // увеличиваем $day
				}
			}
			$calendar_body .= '</tr>'; // закрываем тэг строки
			//$calendar_body .= '<tr class="height"><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>'; // закрываем тэг строки
		}
		return $calendar_body;
	}
	public function actionGetDestination()
	{
		$string = Yii::app()->request->getParam('string');
		$model = City::model()->findAll(
				'LOWER(name) LIKE :name',
				array(':name'=>"%$string%")
		);
		$result = array();
		if ($model) {
			foreach ($model as $key => $value) {
				$result[$key] = array('id' => $value->id, 'name'=>$value->name, 'country'=>$value->country->name);
				echo '<li>'.$value->name.', '.$value->country->name.'</li>';
			}
			//$this->renderPartial('destination', array('result'=>$result));
		} else {
			//$result = array('error'=>'true');
			echo '<li>'.'No result'.'</li>';
		}
		//print json_encode($result);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		// если запрос асинхронный
        if(Yii::app()->request->isAjaxRequest){
        	if (isset($_POST['Booked'])) 
        	{	
            	$booked=new Booked;
            	// $booked->attributes = $_POST['Booked'];
            	// echo var_dump($_POST['Booked']['first_name']);
				$booked->user_id		=	Yii::app()->user->id;
				$booked->first_name		=	$_POST['Booked']['first_name'];
				$booked->last_name		=	$_POST['Booked']['last_name'];
				$booked->object_id		=	Yii::app()->request->getPost('object_id');
				$check_in = explode( '/',$_POST['Booked']['check_in'] );
				if(isset($check_in[2]))
					$booked->check_in	=	$check_in[2] . '-' . $check_in[0] . '-' . $check_in[1];
				$check_out = explode( '/',$_POST['Booked']['check_out'] );
				if(isset($check_out[2]))
					$booked->check_out	=	$check_out[2] . '-' . $check_out[0] . '-' . $check_out[1];
				$booked->guest 			=	$_POST['Booked']['guest'];
				$booked->comment 		=	$_POST['Booked']['comment'];
				$booked->crdate 		=	date("Y-m-d H:i:s");
				if($booked->validate() )
				{
					if($booked->save())
					{
						echo '<br>
							<div class="row cl">
								<div class="message accept br3">'.Yii::t('main', 'You have successfully applied').'</div>
							</div>';
					}
				}
				else
					$this->renderPartial('_booked_popup', array('booked'=>$booked, 'object_id'=>$id));
				Yii::app()->end();
	            
            }
			if (isset($_POST['Review']))
			{
				$review = new Review;
				$review->attributes 	=	$_POST['Review'];
				$review->object_id		=	Yii::app()->request->getPost('object_id');
				$review->user_id		=	Yii::app()->user->id;
				$review->crdate 		=	date("Y-m-d H:i:s");
				/*if($model->validate())
				{

				}*/
				if($review->save())
				{
					Object::setCheckReview($review->object_id);
					// $model = $this->loadModel($id);
					// // echo var_dump($_POST);
					// // $review = $model->CheckReview() ? new Review : NULL;
					// $rating = $model->GetAverageRating();
					
				}
				$model = Object::model()->findByPk($review->object_id,array(
					'select'	=>	'id,
						rating_accuracy,
						rating_communication,
						rating_cleanliness,
						rating_location,
						rating_check_in,
						rating_review,
						rating_average'
				));
				$this->renderPartial('_commentsNew', array(
					'object_id'=>$model->id, 
					'model'=>$model, 
					'review'=>$review, 
					'rating'=>$model->GetAverageRating() ), false, true);
				echo '<ul id="comment_list"><li>
						<div class="date">' . Yii::app()->dateFormatter->format("dd/MM/yyyy", $review->crdate) . '</div>
						<p>' . CHtml::encode($review->text) . '</p>
						<div class="av">
							<a href="' . Yii::app()->createUrl('users/view', array('id'=>$review->user->id)) . '">
								<div class="br5">' . $this->material_image($review->user->id, $review->user->avatar, '68', 'images/' . $review->user->id) . '</div>
								<span>' . CHtml::encode($review->user->full_name) . '</span>
							</a>
						</div></li></ul>
					';
				Yii::app()->end();
			}
        }
        else 
        {
            // если запрос не асинхронный, отдаём форму полностью


			$model = $this->loadModel($id);
			// $review = $model->CheckReview() ? new Review : NULL;
			$rating = $model->GetAverageRating();
			//	Similar Listings
			$similarListings = Object::model()->findAll(array(
				'select'	=>	'id, name, image_id, user_id, room_type_id, price,
					rating_accuracy,
					rating_communication,
					rating_cleanliness,
					rating_location,
					rating_check_in,
					rating_review,
					rating_average',
				'condition'	=>	'`city_id`=:city_id 
					AND `id` NOT IN (:id)
					AND `published`=1',
				'params'	=>	array(
					':city_id'	=>	$model->city_id, 
					':id'		=>	$model->id,
				),
				'limit' 	=> 	10,
				'order' 	=>	'RAND()'
				)
			);
			$booked = new Booked;
			$requestParams['y'] = '2013';
			$requestParams['m'] = '03';
			$requestParams['d'] = '24';
			$calendar_body = self::getCalendarData($requestParams);
			
			//echo $calendar_body;
			/*
			$mvc->addObject ( TemplateEngine::SUCCES, $calendar_body );
			$month_arr = array( 1 => 'Январь', 2 => 'Февраль', 3 => 'Март', 4 => 'Апрель', 5 => 'Май', 6 => 'Июнь', 7 => 'Июль', 8 => 'Август',	9 => 'Сентябрь', 10 => 'Октябрь', 11 => 'Ноябрь', 12 => 'Декабрь');
			$mvc->addObject ( 'mon', $month_arr );
			*/
			$address = $model->country->name .', '. $model->city->name.', '.$model->street.' '.$model->house .'/'.$model->apartment;
			$review = new Review;
			/*if (isset($_POST['Review']) && $model->CheckReview())
			{
				// $review = new Review;
				$review->attributes	=	$_POST['Review'];
				$review->object_id		=	Yii::app()->request->getPost('object_id');
				$review->user_id		=	Yii::app()->user->id;
				$review->crdate 		=	date("Y-m-d H:i:s");
				if($review->save())
				{
					Object::setCheckReview($review->object_id);
					$model = $this->loadModel($id);
					// echo var_dump($_POST);
					// $review = $model->CheckReview() ? new Review : NULL;
					$rating = $model->GetAverageRating();
				}
				else
					echo 'baaad';
			}*/

            $this->render('view',array(
            	'calendar_body'		=>	$calendar_body,
            	'address'			=>	$address,
				'model'				=>	$model,
				'review'			=>	$review,
				'rating'			=>	$rating,
				'user'				=>	$model->user,
				'comments'			=>	$model->comments,
				'booked'			=>	$booked,
				'bookmark'			=>	$model->checkBookmark,
				'similarListings'	=>	$similarListings,
			));
        }
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate($id=NULL, $next_step = NULL, $step=NULL)
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			echo '<pre>';
			var_dump( $_POST );
			echo '</pre>';
			$id  = isset($id) ? $id : Yii::app()->request->getPost('object_id');
			$model=$this->loadModel($id);
			if(isset($_POST['Object']))
			{
				$step = Yii::app()->request->getPost('step');
				$next_step = Yii::app()->request->getPost('next_step');
				$model->attributes 	=	$_POST['Object'];
				if($step == 1) 
				{
					$cityList = City::model()->findAll( array(
						'condition'	=>	'country_id=:country_id',
						'params'	=>	array(':country_id'=>$model->country_id),
						'order'		=>	'name',
					));
					$cityList = CHtml::listData($cityList, 'id', 'name');
				}
				else $cityList = array();
				if($model->save())
				{
					$this->renderPartial('_step_'.$step, array('model'=>$model, 'cityList'=>$cityList));
				}
				Yii::app()->end();
			}
			elseif(isset($_POST['step']))
			{
				$this->SetObjectAmenities($id);
				$mas = $this->GetObjectAmenities($id);
				$this->renderPartial('_step_3',array(
					'object_id'=>$id,
					'model'=>$mas['model'],
					'user'=>$mas['user'],
					'listAmenities'=>$mas['listAmenities'],
				));
			}
			else{
				if($next_step == 1) 
				{
					$cityList = City::model()->findAll( array(
						'condition'	=>	'country_id=:country_id',
						'params'	=>	array(':country_id'=>$model->country_id),
						'order'		=>	'name',
					));
					$cityList = CHtml::listData($cityList, 'id', 'name');
				}
				else $cityList = array();
				if($next_step==3)
				{
					$mas = $this->GetObjectAmenities($id);
					$this->renderPartial('_step_3',array(
						'object_id'=>$id,
						'model'=>$mas['model'],
						'user'=>$mas['user'],
						'listAmenities'=>$mas['listAmenities'],
					));
				}
				else
					$this->renderPartial('_step_'.$next_step, array('model'=>$model, 'cityList'=>$cityList));
				Yii::app()->end();
			}
			
		}
		else
		{
			$model = $this->loadModel($id);

			$user = Users::model()->findByPk(
				Yii::app()->user->id,
				array(
					'select'=>'id, full_name, avatar'
				)
			);
			if(isset($model->country_id)) 
			{
				$cityList = City::model()->findAll( array(
					'condition'	=>	'country_id=:country_id',
					'params'	=>	array(':country_id'=>$model->country_id),
					'order'		=>	'name',
				));
				$cityList = CHtml::listData($cityList, 'id', 'name');
			}
			else $cityList = array();
			$this->render('update',array(
				'model'=>$model,
				'user'=>$user,
				'cityList'=>$cityList,
			));
		}
	}

	public function actionCreate($id = NULL, $step = NULL, $next_step = NULL)
	{
		
		if(Yii::app()->request->isAjaxRequest)
		{
			$id 		=	isset($_POST['object_id'])	?	Yii::app()->request->getPost('object_id') 	: $id;
			$step 		=	isset($_POST['step']) 		?	Yii::app()->request->getPost('step') 		: $id;
			$next_step 	=	isset($_POST['next_step'])	?	Yii::app()->request->getPost('next_step') 	: $next_step;

			if(isset($id)) 
				$model=$this->loadModel($id);
			else {
				$model=new Object;
				$model->user_id		=	Yii::app()->user->id;
				$model->crdate 		=	date("Y-m-d H:i:s");
			}

			if($step == 3) 
				$this->SetObjectAmenities($id);
			else
				$model->attributes 	=	$_POST['Object'];

			if($step == 1) 
			{
				$cityList = City::model()->findAll( array(
					'condition'	=>	'country_id=:country_id',
					'params'	=>	array(':country_id'=>$model->country_id),
					'order'		=>	'name',
				));
				$cityList = CHtml::listData($cityList, 'id', 'name');
			}
			else $cityList = array();
			
			if($model->validate())
			{
				if($model->save())
				{
					if($next_step==3)
					{
						$mas = $this->GetObjectAmenities($id);
						$this->renderPartial('_step_3',array(
							'object_id'=>$id,
							'model'=>$mas['model'],
							'user'=>$mas['user'],
							'listAmenities'=>$mas['listAmenities'],
						));
					}
					else
					{
						$this->renderPartial('_step_'.$next_step, array('model'=>$model, 'cityList'=>$cityList));
					}
				}
			}
			else
			{
				$this->renderPartial('_step_' . $step, array('model'=>$model, 'cityList'=>$cityList));
			}
		
            Yii::app()->end();
        }
        else
        {
			$model = isset($id) ? $this->loadModel($id) : new Object;
			if(isset($_POST['Object']))
			{
				$model->attributes 	=	$_POST['Object'];
				$model->user_id		=	Yii::app()->user->id;
				$model->crdate 		=	date("Y-m-d H:i:s");
				if($model->save())
					$this->redirect(array('view','id'=>$model->id));
			}
			$user = Users::model()->findByPk(
				Yii::app()->user->id,
				array(
					'select'=>'id, full_name, avatar'
				)
			);
			if(isset($model->country_id)) 
			{
				$cityList = City::model()->findAll( array(
					'condition'	=>	'country_id=:country_id',
					'params'	=>	array(':country_id'=>$model->country_id),
					'order'		=>	'name',
				));
				$cityList = CHtml::listData($cityList, 'id', 'name');
			}
			else $cityList = array();
			$this->render('create',array(
				'model'=>$model,
				'user'=>$user,
				'cityList'=>$cityList,
			));
        }	
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria=new CDbCriteria;
		$with = array();
		if(!empty($_GET['continent']))
		{
			$continent =  implode(",", array_keys($_GET['continent']));
			$with['country'] = array(
		        'select'=>false,
		        'joinType'=>'INNER JOIN',
		        'condition'=>'country.continent IN (' . $continent . ')',
			);
		}
		if(!empty($_GET['destination']))
		{
			$destination = explode( ', ',$_GET['destination'] );
			if (isset($destination[1]))
			{
				$with['city'] = array(
			        'select'=>false,
			        'joinType'=>'INNER JOIN',
			        'condition'=>'city.name=:name',
			        'params'=>array(':name'=>$destination[0]),
			        'with'=> array(
			        	'country'=>array(
			        		'select'=>false,
			        		'condition'=>'country.name=:country_name',
			        		'params'=>array(':country_name'=>$destination[1])
			        	)
			        ),
				);
			}
			else
			{
				$with['city'] = array(
			        'select'=>false,
			        'joinType'=>'INNER JOIN',
			        'condition'=>'city.name=:name',
			        'params'=>array(':name'=>$destination[0]),
				);
			}
		}
		/*if( !empty($_GET['check_in']) && !empty($_GET['check_out']))
		{
			$check_in = new DateTime($_GET['check_in']);
			$check_out = new DateTime($_GET['check_out']);
			$with['booked_days'] = array(
		        // 'select'=>false,
		        'joinType'=>'INNER JOIN',
				'condition'=>"booked_date NOT BETWEEN ':check_in' AND ':check_out'",
				'params'=>array(':check_in'=>$check_in->format('Y-m-d'), ':check_out'=>$check_out->format('Y-m-d')),
				'group'=>'object_id',
			);
		}*/
		$criteria->with= $with;
		$criteria->condition='`published`="1"';
		if( !empty($_GET['check_in']) && !empty($_GET['check_out']))
		{
			$check_in = new DateTime($_GET['check_in']);
			$check_out = new DateTime($_GET['check_out']);
			$booked_object = BookedTemp::model()->findAll(array(
				'select'=>'id, object_id',
				'condition'=>'booked_date BETWEEN :check_in AND :check_out',
				'params'=>array(':check_in'=>$check_in->format('Y-m-d'), ':check_out'=>$check_out->format('Y-m-d')),
				'group'=>'object_id',
			));
			$list_booked_object = CHtml::listData($booked_object,'object_id', 'id');
			$criteria->addNotInCondition('t.id', array_keys($list_booked_object), 'AND');
		}
		elseif( !empty($_GET['check_in']) || !empty($_GET['check_out']))
		{
			echo Yii::t('main', 'Error date');
		}
		if(!empty($_GET['roomType']))
		{
			$criteria->addInCondition( 'room_type_id', array_keys($_GET['roomType']), 'AND' );
		}
		if( !empty($_GET['from_price']) && !empty($_GET['until_price']) )
		{
			$criteria->addBetweenCondition( 'price', $_GET['from_price'], $_GET['until_price'], 'AND' );
		}
		elseif ( !empty($_GET['from_price']) ) {
			$criteria->addCondition( 'price>=' . $_GET['from_price'], 'AND' );
		}
		elseif ( !empty($_GET['until_price']) ) {
			$criteria->addCondition( 'price<=' . $_GET['until_price'], 'AND' );
		}
		$cityList = array();
		if( !empty($_GET['country']) )
		{
			$criteria->addCondition( 'country_id=' . $_GET['country'], 'AND' );
			$cityList = City::model()->findAll( array(
				'condition'	=>	'country_id=:country_id',
				'params'	=>	array(':country_id'=>$_GET['country']),
				'order'		=>	'name'
			));
			$cityList = CHtml::listData($cityList, 'id', 'name');
		}
		if( !empty($_GET['city']) && (int)$_GET['city'] > 0 )
		{
			$criteria->addCondition( 'city_id=' . (int)$_GET['city'], 'AND' );
		}
		// $criteria->params=array(':postID'=>10);
		$dataProvider = Object::model()->findAll($criteria);
		$roomType = RoomType::model()->findAll();
		$this->render('index',array(
			'roomType'=>$roomType,
			'cityList'=>$cityList,
			'dataProvider'=>$dataProvider,
		));
	}

	

	public function actionCheckBooked()
	{
		$booked = new Booked;
		if(isset($_POST['Booked']))
		{
			$booked->user_id		=	Yii::app()->user->id;
			$booked->object_id		=	Yii::app()->request->getPost('object_id');

			if( !empty( $_POST['Booked']['check_in'] ) && !empty( $_POST['Booked']['check_out'] ) )
			{
				$check_in = new DateTime($_POST['Booked']['check_in']);
				$booked->check_in	=	$check_in->format('Y-m-d H:i:s');
				$check_out = new DateTime($_POST['Booked']['check_out']);
				$booked->check_out	=	$check_out->format('Y-m-d H:i:s');
				// total price
				$interval = date_diff($check_in, $check_out);
				$total_price = 0;
				/*echo '<pre>';
				var_dump($interval);
				echo '</pre>';*/
				if ($interval->y)
				{
					$total_price += $interval->y * 12 * $booked->object->price_month;
				}
				if ($interval->m)
				{
					$total_price += $interval->m * $booked->object->price_month;
				}
				if ($interval->d)
				{
					if($interval->d < 7)
						$total_price += $interval->d * $booked->object->price;
					else
					{
						$total_price += ( (int)($interval->d / 7) * $booked->object->price_week ) + ( $interval->d % 7 * $booked->object->price );
					}
				}
				$booked->total_price = $total_price;
				// END total price
			}
			$booked->guest 			=	$_POST['Booked']['guest'];
			$booked->crdate 		=	date("Y-m-d H:i:s");
			if($booked->validate() )
			{
				if($booked->save())
				{
					$name = explode(' ',Yii::app()->user->name);
					$booked->first_name = $name[0];
					$booked->last_name = $name[1];
					$this->renderPartial('_booked_popup', array('booked'=>$booked, 'object_id'=>Yii::app()->request->getPost('object_id')));
				}
			}
			else
				echo '<br>
					<div class="row cl">
						<div class="message error br3">'.Yii::t('main', 'You have valid error').'</div>
					</div>';
			Yii::app()->end();
		}		
	}
	public function actionBooked()
	{
		$booked = Booked::model()->findByPk(Yii::app()->request->getPost('booked_id'));
		$booked->scenario='booking';
		$booked->attributes = $_POST['Booked'];
		if( $booked->validate() )
		{
			if($booked->save())
			{
				$date = new DateTime($booked->check_in);
				$interval = $date->diff(new DateTime($booked->check_out));
				for ($i=0; $i < $interval->days; $i++) { 
					$booked_day = new BookedTemp;
					$booked_day->object_id	=	$booked->object_id;
					$booked_day->booked_id	=	$booked->id;
					$booked_day->booked_date=	$date->format('Y-m-d');
					$booked_day->save();
					$date->modify('+1 day');
				}
				echo '<div class="row cl">
						<div class="message accept br3">'.Yii::t('main', 'You have successfully applied').'</div>
					</div>';
			}
		}
		else
		{
			$this->renderPartial('_booked_popup', array('booked'=>$booked, 'object_id'=>Yii::app()->request->getPost('object_id')));
		}

	}

	public function actionAddBookmark($object)
	{
		$model = new Favorites;
		$model->user_id 	= Yii::app()->user->id;
		$model->object_id	= $object;
		$model->save();
		//$this->redirect(array('view','id'=>$object));
		$data = Object::model()->findByPk($object,array('select'=>'id'));
		$bookmark 		= $data->checkBookmark;
		$countBookmark	= $data->countBookmark;
        $this->renderPartial('_bookmark', array('bookmark'=>$bookmark,'object'=>$object, 'countBookmark'=>$countBookmark));
        Yii::app()->end();
	}

	public function actionDelBookmark($object,$favorite)
	{
		Favorites::model()->deleteByPk($favorite);
		$data = Object::model()->findByPk($object,array('select'=>'id'));
		$bookmark 		= $data->checkBookmark;
		$countBookmark 	= $data->countBookmark;
		// $this->redirect(array('view','id'=>$object));
		$this->renderPartial('_bookmark', array('bookmark'=>$bookmark,'object'=>$object, 'countBookmark'=>$countBookmark));
		Yii::app()->end();
	}

	public function actionUploadPhoto(){
		$model=new Images;
		$model->object_id = Yii::app()->request->getParam('id');
		$path = $_SERVER['DOCUMENT_ROOT'].'/upload/images/'.Yii::app()->user->id.'/'.Yii::app()->request->getParam('id').'/';
		$model->name = self::savePhoto($_FILES['image'], $path);
		$model->save();
		$avatar = Object::model()->findByPk($model->object_id);
		if(!isset($avatar->image_id)) $avatar->image_id = $model->id;
		$avatar->save();
		echo "{";
		echo	"msg: '" . Yii::app()->request->getParam('id') . "',\n";
		echo "}";
	}
	
	public function actionListPhoto()
	{
		$model = Object::model()->findByPk(Yii::app()->request->getParam('id'));
		$images = $model->images;
		$user = $model->user;
		$this->renderPartial('_listPhoto', array('images'=>$images,'user'=>$user));
	}

	public function actionGetListCity($country_id)
	{
		$model = City::model()->findAll(array(
			'condition'	=> 'country_id=:country_id',
			'params'	=>	array(':country_id'=>$country_id),
			'order'		=>	'name',
		));	
		$cities = array();
		if ($model) {    
		    foreach ($model as $key => $value) {
		       $cities[$key] = array('id' => $value->id, 'name'=>$value->name);  
		    }    
		    $result = array('cities'=>$cities); 
		}
		else {
		    $result = array('type'=>'error');
		}
		print json_encode($result);
	}

	/**
	 * Rating Review
	 *	
     * Set mark for the good by user
     * @param $object_id
     * @param $rate mark (1-5)
     */
    public function actionSetMark($object_id, $rate, $attribute)
    {
        if (Yii::app()->user->isGuest) {
            echo 'you are not registered user';
            return;
        }
        $user = Yii::app()->user->id;
        $rating = Review::model()->with(array(
	        	'object', 
	        	'object.marksCount'
	        ))->findByAttributes(array(
				'user_id' => $user,
				'object_id' => $object_id,
			));
        if (empty($rating)) 
        { // если никто не оценивал статью ещё
            if ($rate == 'undefined') 
            {
                return;
            }

            $rating = new Review;
            $rating->object_id = $object_id;
            $rating->user_id = $user;
            $rating->crdate = date("Y-m-d H:i:s");
            $rating->$attribute = $rate;
            if ($rating->save()) 
            {
				$good = $rating->object;
				$good->$attribute = round($good->$attribute + ($rate * 100 - $old_mark * 100) / $good->marksCount) ;
				$good->save();
				echo 'success';
				/*$model = Object::findByPk($object_id);
				$this->renderPartial('_stars', array('model'=>$model));
				Yii::app()->end();*/
            }
            else
                echo 'fail saving';
        } 
        else 
        {
            if ($rating->$attribute != $rate) 
            {
                if ($rate == 'undefined') 
                {
                    echo 'rate deleted';
                    $rating->delete();
                    return;
                }
                $old_mark = $rating->$attribute;
                $rating->$attribute = $rate;
                if ($rating->save()) {
                    $good = $rating->object;
                    $good->$attribute = round($good->$attribute + ($rate * 100 - $old_mark * 100) / $good->marksCount) ;
                    $good->save();
                    echo 'success';
					/*$model = Object::findByPk($object_id);
					$this->renderPartial('_stars', array('model'=>$model));
					Yii::app()->end();*/
                }
                else
                    echo 'fail saving';
            } else
                echo 'no need to change';
        }
    }
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Object::model()->findByPk($id);
		
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function SetObjectAmenities($id)
	{
		$amenity = Yii::app()->request->getPost('amenity');
		$model = ObjectAmenities::model()->findAll(
				'object_id=:object_id',
				array(':object_id'=>$id)
			);
			if(isset($amenity)) {
				foreach ($model as $key => $value) {
					if(!array_key_exists($value->amenities_id, $amenity)) $value->delete();
				}
				foreach ($amenity as $key => $value) {
					$newAm = new ObjectAmenities;
					$newAm->object_id = $id;
					$newAm->amenities_id = $key;
					$newAm->save();
				}
			}
			else
			{
				foreach ($model as $amenity) {
					$amenity->delete();
				}
			}
	}

	public function GetObjectAmenities($id)
	{
		$listAmenities = Amenities::model()->findAll();
		$model = ObjectAmenities::model()->findAll(
			'object_id=:object_id',
			array(':object_id'=>$id)
		);

		$user = Users::model()->findByPk(
			Yii::app()->user->id,
			array(
				'select'=>'id, full_name, avatar'
			)
		);
		$mas = array();
		$mas['listAmenities']	=	$listAmenities;
		$mas['model']			=	$model;
		$mas['user']			=	$user;
		return $mas;
	}
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='object-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
